<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category SwooleCommand.php
 * @Depiction:
 * Author: hwy
 * Date: 2020/6/3  10:30
 * +--------------------------------------------------------+
 */

namespace App\Console\Commands;

use App\Models\Stock;
use App\Services\StockService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class WebSwooleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'web_swoole {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开启 websocket 服务';

    private $ws;
    private $start_t;
    private $end_t;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $arg = $this->argument('action');

        switch ($arg) {
            case 'start':
                $this->info('swoole observer started');
                $this->start();
                break;
            case 'stop':
                $this->info('stoped');
                break;
            case 'restart':
                $this->info('swoole observer restarted');
                $this->reload();
                break;
            default:
                $this->error("unknown command");
        }
    }

    public function start()
    {
        //创建websocket服务器对象，监听0.0.0.0:9502端口
//        $this->ws = new \swoole_websocket_server("0.0.0.0", 9502);
        $this->ws = new \swoole_websocket_server("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
        $this->ws->set([
            'worker_num'               => 4,
            'heartbeat_check_interval' => 60, // 60秒检测一次
            'heartbeat_idle_time'      => 120, // 120秒没活动的
            'ssl_key_file' => '/usr/local/nginx/conf/ssl/han920.com/2_han920.com.key',
            'ssl_cert_file' => '/usr/local/nginx/conf/ssl/han920.com/1_han920.com_bundle.crt'
        ]);

        //监听WebSocket连接打开事件
        $this->ws->on('open', function ($ws, $request) {
            var_dump($request->fd . "连接成功");
            // $ws->push($request->fd, "hello, welcome\n");
        });

        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
            $this->start_t = microtime(true);
            $get_url = config('other.stock_url');
            $stock_list = StockService::getInstance()->getAll(2);

            $data     = StockService::getInstance()->get_stock_real_time($stock_list, $get_url);
            $data_cap = StockService::getInstance()->get_stock_real_time_cap($stock_list, $get_url);
            $indexs   = StockService::getInstance()->getStockNum();
            $list     = [];
            foreach ( $data as $key => $vo ) {
                $list[] = array_merge($vo, $data_cap[$key]);
            }
            $lists['data']   = $list;
            $lists['indexs'] = $indexs;

            $lists = json_encode($lists);
            $this->end_t = microtime(true);
            $t = ($this->end_t -  $this->start_t) * 1000 . 'ms';
            echo "{$frame->fd}_Message: {$t}\n";
            $ws->push($frame->fd, $lists);
            // var_dump($ws->connection_info($frame->fd));
            //fd绑定客户端传过来的标识uid
//            $ws->bind($frame->fd, $frame->data);
        });


        //监听WebSocket主动推送消息事件
        $this->ws->on('request', function ($request, $response) {
            $scene = $request->post['scene'];       // 获取值
            $this->info("client is PushMessage\n" . $scene);
        });
        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            echo "client:{$fd} is closed\n";
        });

        $this->ws->start();
    }


    private function reload()
    {
        $this->ws = new \swoole_websocket_server("0.0.0.0", 9502);
        $this->ws->reload();
//         \swoole_server::reload();
    }

}
